package com.springcloud.zuul.common.utlis;

import com.alibaba.fastjson.JSON;
import com.springcloud.zuul.common.constant.ServiceErrCode;
import com.springcloud.zuul.entity.SysUserVo;
import com.springcloud.zuul.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: springcloud-zuul
 * @description: 用户缓存
 * @author: zhlu
 * @create: 2020-01-02 16:54
 * @Introduction(说明背景故事)
 **/
@Slf4j
public class ContextUtils {

    private ContextUtils(){
        log.info("");
    }

    private static final ThreadLocal<Map<String,Object>>THREAD_LOCAL=new InheritableThreadLocal<>();
    private static final String USERKEY="userKey";
    private static final String HEAD_TYPE="user_type";

    /**
     * Description:赋值用户信息
     * @author zhlu
     * @date 2019/12/30 10:30 上午
     * @param userJson
     * @param cls
     * @param code
     * @return void
     */
    public static void setUser(String userJson, Class cls, Integer code) {

        if (StringUtils.isBlank(userJson) || code == null || cls == null) {
            throw new ServiceException(ServiceErrCode.INVALID_PARAMS);
        }
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();

        Object loginUserVo = JSON.parseObject(userJson, cls);
        map.put(USERKEY, loginUserVo);
        map.put(HEAD_TYPE, code);
        THREAD_LOCAL.set(map);
    }

    /**
     * Description:获取用户信息
     * @author zhlu
     * @date 2019/12/30 10:45 上午
     * @param
     * @return com.springcloud.zuul.entity.SysUserVo
     */
    public static SysUserVo getUser() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            throw new ServiceException("{\"msg\":\"用户未登录!\",\"code\":300}");
        }
        return (SysUserVo) map.get(USERKEY);
    }

    /**
     * Description:获取用户id
     * @author zhlu
     * @date 2019/12/30 10:50 上午
     * @param
     * @return java.lang.String
     */
    public static String getUserId() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (MapUtils.isEmpty(map)) {
            throw new ServiceException("{\"msg\":\"用户未登录!\",\"code\":300}");
        }
        return String.valueOf(((SysUserVo) map.get(USERKEY)).getUserId());
    }

    public static void close() {
        THREAD_LOCAL.remove();
    }
}
